package com.taxi.driver.module.main.mine.wallet.withdrawal;

import com.qianxx.network.RequestError;
import com.qianxx.utils.RxUtil;
import com.qianxx.utils.encode.RandomUtil;
import com.socks.library.KLog;
import com.taxi.driver.R;
import com.taxi.driver.common.BasePresenter;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.module.vo.WithdrawalVO;

import javax.inject.Inject;

public class WithdrawalPresenter extends BasePresenter implements WithdrawalContract.Presenter {

    private WithdrawalContract.View mView;
    private UserRepository mUserRepository;

    @Inject
    public WithdrawalPresenter(UserRepository userRepository, WithdrawalContract.View view) {
        mUserRepository = userRepository;
        mView = view;
    }

    @Override
    public void reqDriverInfo() {
        mUserRepository.refreshUserInfo();
        mUserRepository.getUserInfo()
                .map(WithdrawalVO::createFrom)
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(false))
                .doAfterTerminate(() -> mView.hideLoadingView())
                .subscribe(vo -> mView.showDriverInfo(vo),
                        KLog::e);
    }

    @Override
    public void withdrawal(String cash, String collectAccount, int collectType, String password) {
        mUserRepository.withdrawal(RandomUtil.RandomEncrypt(cash), RandomUtil.RandomEncrypt(collectAccount),
                collectType, RandomUtil.RandomEncrypt(password))
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(true))
                .doAfterTerminate(() -> mView.hideLoadingView())
                .subscribe(driverEntity -> mView.withdrawalSucc(),
                        ex -> {
                            showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                            Throwable throwable = ex.getCause();
                            if (throwable instanceof RequestError) {
                                RequestError error = ((RequestError) throwable);
                                mView.withdrawalFail(error.getErrCode(), error.getMessage());
                            }
                        });
    }
}
